from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users.models import User
from .serializers import RegisterCreateSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer, \
    UserHistorySerializer, SKUSerializer
from rest_framework import status
from rest_framework.decorators import action
from .serializers import AddressTitleSerializer
from django_redis import get_redis_connection
from goods.models import SKU


class RegisterUsernameCountAPIView(APIView):
    """
       获取用户名的个数
       GET:  /users/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        context = {
            'count': count,
            'username': username,
        }
        return Response(context)


class RegisterMoblieCountAPIView(APIView):
    """
       获取手机号的个数
       GET:  /users/mobile/(?P<mobile>[3-9]\d{11})/count/
    """

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        context = {
            'count': count,
            'phone': mobile,
        }
        return Response(context)


# 第一级视图
class RegisterCreateView(APIView):
    def post(self, request):
        serializer = RegisterCreateSerializer(data=request.data)
        serializer.is_valid()
        serializer.save()
        return Response(serializer.data)


# 第二级视图
# from rest_framework.mixins import CreateModelMixin
# class RegisterCreateView(GenericAPIView, CreateModelMixin):
#     serializer_class = RegisterCreateSerializer
#
#     def post(self, request):
#         return self.create(request)

# 第三级视图
# class RegisterCreateView(CreateAPIView):
#     serializer_class = RegisterCreateSerializer

# class UserDetailView(GenericAPIView):
#     permission_classes = [IsAuthenticated]
#
#     def get(self, requset):
#         user = requset.user
#         serializer = UserDetailSerializer(user)
#         return Response(serializer.data)

class UserDetailView(RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user


class VerificationEmailView(APIView):
    """
    验证激活邮箱
    GET /users/emails/verification/?token=xxxx

    思路:
    获取token,并判断
    获取 token中的id
    查询用户,并判断是否存在
    修改状态
    返回响应
    """

    def get(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'ok'})


class AddressViewSet(ListModelMixin, CreateModelMixin, UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    # 制定序列化器
    serializer_class = AddressSerializer
    # 添加用户权限
    permission_classes = [IsAuthenticated]

    # 由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message': '保存地址数量已经达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


class UserHistoryView(GenericAPIView):
    # POST    /users/browerhistories/       {'sku_id':xxx}  新增历史记录
    permission_classes = [IsAuthenticated]
    pagination_class = None
    serializer_class = UserHistorySerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        # 数据校验
        serializer.is_valid()
        # 数据保存
        serializer.save()

        return Response(serializer.data)

    # def get(self, request):
    #     # 1.连接redis数据库
    #     redis_conn = get_redis_connection('history')
    #     # 2.查询前五个浏览历史商品id
    #     redis_ids = redis_conn.lrange('history_%s'%request.user.id,0,5)
    #     # 3. 我们需要根据id来获取商品的详细信息
    #     # skus = SKU.objects.filter(id__in=redis_ids)
    #     skus = []
    #     for sku_id in redis_ids:
    #         skus = SKU.objects.get(pk=sku_id)
    #         skus.append(skus)
    #     serializer = SKUSerializer(instance=skus,many=True)
    #     return Response(serializer.data)

    def get(self, request):
        # 2. 获取redis中的数据 (sku_id,sku_id)
        redis_conn = get_redis_connection('history')

        redis_ids = redis_conn.lrange('history_%s' % request.user.id, 0, 5)
        # [id,id,id]
        # 3. 我们需要根据id来获取商品的详细信息
        # skus = SKU.objects.filter(id__in=redis_ids)
        # 如果我们按照 SKU.objects.filter(id__in=redis_ids) 语句查询商品的详细信息
        # 确实可以查询出来,但是商品的顺序被改变了,
        # 我们需要保留原来的顺序
        skus = []

        for sku_id in redis_ids:
            sku = SKU.objects.get(pk=sku_id.decode())
            skus.append(sku)

        # [SKU,SKU,SKU]
        # 4. 商品的详细信息是模型,需要将模型转换为字典
        serializer = SKUSerializer(instance=skus, many=True)

        return Response(serializer.data)


from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cookie_to_redis


class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cart_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response
